package org.rslai.autotest.core.page.impl;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.rslai.autotest.core.page.AbstractHelper;
import org.rslai.autotest.core.page.Robot;
import org.rslai.autotest.core.page.Script;
import org.rslai.util.imageprocess.position.Area;
import org.rslai.util.imageprocess.position.SpecifiedRegion;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Robot处理方法
 * @author rslai
 */
public class RobotImpl extends AbstractHelper implements Robot {
	@Autowired
	protected Script script;

	@Override
	public void openModalDialog(By by)  {
		this.driver().findElement(by).sendKeys("");
		try {
			java.awt.Robot robot = new java.awt.Robot();
			robot.keyPress(KeyEvent.VK_ENTER); 
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void click(By by) throws AWTException, IOException {
		this.click(by, -30000, -30000);
	}

	@Override
	public void click(By by, int xOffset, int yOffset) throws AWTException, IOException {
		script.highlight(by);
		super.sleep(1);

		Area area = new SpecifiedRegion().getSpecifiedRegion(Color.YELLOW, 5);
		if (area == null) {
			throw new NoSuchElementException("未能定位到颜色为 " + Color.YELLOW + " 宽度为 5 的区块");
		} else {
			int x;
			int y;
			if (xOffset==-30000 && yOffset==-30000) {
				x = area.getX() + 5 + (area.getWidth()-10) / 2;
				y = area.getY() + 5 + (area.getHeight()-10) /2;
			} else {
				x = area.getX() + 5 + xOffset;
				y = area.getY() + 5 + yOffset;
			}

			java.awt.Robot robot = new java.awt.Robot();
			robot.mouseMove(x, y);
			super.sleep(1);
			robot.mousePress(InputEvent.BUTTON1_MASK);
			super.sleep(1);
			robot.mouseRelease(InputEvent.BUTTON1_MASK);
		}

		this.sleep(this.conf.getDriverPlaybackSpeed()); // 设置回放速度		
	}

}
